package cn.iocoder.yudao.module.book.service.admin.bookshelfcatalogue;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.controller.admin.bookshelfcatalogue.vo.BookShelfCataloguePageReqVO;
import cn.iocoder.yudao.module.book.controller.admin.bookshelfcatalogue.vo.BookShelfCatalogueSaveReqVO;
import cn.iocoder.yudao.module.book.dal.dataobject.bookshelfcatalogue.BookShelfCatalogueDO;
import cn.iocoder.yudao.module.book.dal.mysql.bookshelfcatalogue.BookShelfCatalogueMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.SHELF_CATALOGUE_NOT_EXISTS;

/**
 * 绘本分类 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BookShelfCatalogueServiceImpl implements BookShelfCatalogueService {

    @Resource
    private BookShelfCatalogueMapper shelfCatalogueMapper;

    @Override
    public Long createShelfCatalogue(BookShelfCatalogueSaveReqVO createReqVO) {
        // 插入
        BookShelfCatalogueDO shelfCatalogue = BeanUtils.toBean(createReqVO, BookShelfCatalogueDO.class);
        shelfCatalogueMapper.insert(shelfCatalogue);

        // 返回
        return shelfCatalogue.getId();
    }

    @Override
    public void updateShelfCatalogue(BookShelfCatalogueSaveReqVO updateReqVO) {
        // 校验存在
        validateShelfCatalogueExists(updateReqVO.getId());
        // 更新
        BookShelfCatalogueDO updateObj = BeanUtils.toBean(updateReqVO, BookShelfCatalogueDO.class);
        shelfCatalogueMapper.updateById(updateObj);
    }

    @Override
    public void deleteShelfCatalogue(Long id) {
        // 校验存在
        validateShelfCatalogueExists(id);
        // 删除
        shelfCatalogueMapper.deleteById(id);
    }

    @Override
    public void deleteShelfCatalogueListByIds(List<Long> ids) {
        // 删除
        shelfCatalogueMapper.deleteByIds(ids);
    }


    private void validateShelfCatalogueExists(Long id) {
        if (shelfCatalogueMapper.selectById(id) == null) {
            throw exception(SHELF_CATALOGUE_NOT_EXISTS);
        }
    }

    @Override
    public BookShelfCatalogueDO getShelfCatalogue(Long id) {
        return shelfCatalogueMapper.selectById(id);
    }

    @Override
    public PageResult<BookShelfCatalogueDO> getShelfCataloguePage(BookShelfCataloguePageReqVO pageReqVO) {
        return shelfCatalogueMapper.selectPage(pageReqVO);
    }

    @Override
    public String getCatalogueNameById(Long catalogueId) {
        BookShelfCatalogueDO bookShelfCatalogueDO = shelfCatalogueMapper.selectById(catalogueId);
        if (bookShelfCatalogueDO == null) {
            return null;
        }
        return bookShelfCatalogueDO.getCategoryName();
    }

}